package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.key.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie的工具类
 */
public class CookieUtil {

    /**
     * 添加cookie
     */
    public static void addCookie(String key, String token, HttpServletResponse resp,int time){
        //存进cookie里
        Cookie cookie = new Cookie("token",token);
        //设置cookie作用域
        cookie.setPath("/");
        //设置cookie最大存活时间
        cookie.setMaxAge(time);
        resp.addCookie(cookie);
    }

    /**
     * 获取登录的token
     */
    public static String getToken(HttpServletRequest req,HttpServletResponse resp){
        //从请求中获取cookie数组
        Cookie[] cookies = req.getCookies();
        //判断有没有拿到cookie
        if(cookies != null){
            for (Cookie cookie : cookies){
                if("token".equals(cookie.getName())){
                    //延长cookie的时间
                    cookie.setMaxAge(RedisKeys.USER_INFO_LOGIN.getTime().intValue());
                    cookie.setPath("/");
                    resp.addCookie(cookie);

                    //返回cookie的值
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
